package com.xnx.bincker.leader.core.security;

import com.xnx.bincker.leader.domain.User;
import com.xnx.bincker.leader.exception.permission.NoLoginException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 获取当前用户工具
 */
public class SecurityUserHolder {
    public static Optional<User> getCurrentUser(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if(securityContext == null) return Optional.empty();
        Authentication authentication = securityContext.getAuthentication();
        if(authentication == null) return Optional.empty();
        Object user = authentication.getPrincipal();
        if(user instanceof User){
            return Optional.of((User) user);
        }
        return Optional.empty();
    }

    public static User currentUser(){
        return getCurrentUser().orElseThrow(NoLoginException::new);
    }
}
